package com.grad.why.studentsystem.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.grad.why.studentsystem.domain.Classinfo;
import com.grad.why.studentsystem.domain.Project;
import com.grad.why.studentsystem.domain.Student;
import com.grad.why.studentsystem.mapper.ClassinfoMapper;
import com.grad.why.studentsystem.mapper.ProjectMapper;
import com.grad.why.studentsystem.mapper.StudentMapper;
import com.grad.why.studentsystem.service.StudentService;
import com.grad.why.studentsystem.service.StudentarrivedinfoService;
import com.grad.why.studentsystem.util.Util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Service(interfaceClass = StudentService.class)
@Transactional

public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassinfoMapper classinfoMapper;

    @Autowired
    private ProjectMapper projectMapper;

    /**
     * 获取学生信息
     * @param offset
     * @param limit
     * @param sort
     * @param search
     * @return
     */
    @Override
    public List<Student> getStudentList(int offset, int limit, String sort, String search) {
        try{
            ArrayList<Student> students = studentMapper.getStudentList(offset,limit,sort,search);
            return students;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long getStudentListLength(String search) {
        try{
            long length = studentMapper.getStudentListLength(search);
            return length;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int getMaxStudentId() {
        return studentMapper.getMaxId();
    }

    @Override
    public Student addStudentByEntity(Student student) {
        try{
            int n = studentMapper.insertSelective(student);
            if(n > 0){
                Classinfo classinfo = classinfoMapper.selectByPrimaryKey(student.getClassid());
                Project project = projectMapper.selectByPrimaryKey(classinfo.getProjectid());
                classinfo.setStudentcount(classinfo.getStudentcount() + 1);
                project.setStudentcount(project.getStudentcount() + 1);
                classinfoMapper.updateByPrimaryKeySelective(classinfo);
                projectMapper.updateByPrimaryKeySelective(project);
                return student;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int deleteStudentById(Integer id) {
        try{
            Student student = studentMapper.selectByPrimaryKey(id);
            int rows = studentMapper.deleteByPrimaryKey(id);
            if(rows > 0){
                Classinfo classinfo = classinfoMapper.selectByPrimaryKey(student.getClassid());
                classinfo.setStudentcount(classinfo.getStudentcount() - 1);
                Project project = projectMapper.selectByPrimaryKey(classinfo.getProjectid());
                project.setStudentcount(project.getStudentcount() - 1);
                classinfoMapper.updateByPrimaryKey(classinfo);
                projectMapper.updateByPrimaryKey(project);
            }
            return rows;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }

    //修改学生信息
    @Override
    public Student updateStudentByEntity(Student student) {
        try{
            int id = student.getId();
            Student oriStudent = studentMapper.selectByPrimaryKey(id);
            if(oriStudent.getClassid() == student.getClassid()){
                studentMapper.updateByPrimaryKey(student);
            }else{
                Classinfo oriClassinfo = classinfoMapper.selectByPrimaryKey(oriStudent.getClassid());
                oriClassinfo.setStudentcount(oriClassinfo.getStudentcount() - 1);
                Classinfo newClassinfo = classinfoMapper.selectByPrimaryKey(student.getClassid());
                newClassinfo.setStudentcount(newClassinfo.getStudentcount() + 1);
                studentMapper.updateByPrimaryKey(student);
                classinfoMapper.updateByPrimaryKey(oriClassinfo);
                classinfoMapper.updateByPrimaryKey(newClassinfo);
            }
            return student;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getStudentNameBySid(int sid) {
        try{
            Student student = studentMapper.selectByPrimaryKey(sid);
            if(student == null){
                return null;
            }else{
                return student.getName();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addStudentInfosByExcelFile(String uploadCurrentFileName) {
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            DecimalFormat decimalFormat = new DecimalFormat("##0");//格式化设置
            InputStream is = new FileInputStream(uploadCurrentFileName);
            Workbook wb = null;
            int realAddPersonCount = 0;
            if(uploadCurrentFileName.split("\\.")[1].equals("xls")){
                wb = new HSSFWorkbook(is);
            }else if(uploadCurrentFileName.split("\\.")[1].equals("xlsx")){
                wb = new XSSFWorkbook(is);
            }

            int sheetNumber = wb.getNumberOfSheets();
            int InsertCount = 0;
            Row title = wb.getSheetAt(0).getRow(0);
            if(!title.getCell(0).getStringCellValue().equals("姓名")||
                    !title.getCell(1).getStringCellValue().equals("性别")||
                    !title.getCell(2).getStringCellValue().equals("年龄")||
                    !title.getCell(3).getStringCellValue().equals("出生日期")||
                    !title.getCell(4).getStringCellValue().equals("民族")||
                    !title.getCell(5).getStringCellValue().equals("班级")||
                    !title.getCell(6).getStringCellValue().equals("电话")||
                    !title.getCell(7).getStringCellValue().equals("地址")||
                    !title.getCell(8).getStringCellValue().equals("设备信息")){
                return 0;
            }

            for(int i = 0;i<sheetNumber;i++) {
                int index = 1;
                for(Row row : wb.getSheetAt(i)){
                    if(row == null){
                        continue;
                    }else{
                        if(index == 1){

                        }else{
                            if(row.getCell(0) == null){
                                index++;
                                continue;
                            }else{
                                Student student = new Student();
                                student.setId(studentMapper.getMaxId() + 1);
                                student.setName(Util.formGetCellType(row.getCell(0)));
                                student.setSex(Util.formGetCellType(row.getCell(1)));
                                student.setAge(Integer.parseInt(Util.formGetCellType(row.getCell(2))));
                                student.setBirthday(sdf.parse(Util.formGetCellType(row.getCell(3))));
                                student.setNation(Util.formGetCellType(row.getCell(4)));
                                int classId = classinfoMapper.getClassIdByClassName(Util.formGetCellType(row.getCell(5)));
                                student.setClassid(classId);
                                student.setTel(Util.formGetCellType(row.getCell(6)));
                                student.setAddress(Util.formGetCellType(row.getCell(7)));
                                student.setDeviceinfo(Util.formGetCellType(row.getCell(8)));

                                studentMapper.insertSelective(student);
                                InsertCount = InsertCount + 1;
                                realAddPersonCount = realAddPersonCount + 1;
                                //更新班级人数
                                Classinfo classinfo = classinfoMapper.selectByPrimaryKey(classId);
                                classinfo.setStudentcount(classinfo.getStudentcount() + 1);
                                classinfoMapper.updateByPrimaryKey(classinfo);

                                //更新专业人数
                                Project project = projectMapper.selectByPrimaryKey(classinfo.getProjectid());
                                project.setStudentcount(project.getStudentcount() + 1);
                                projectMapper.updateByPrimaryKey(project);
                            }
                        }
                        index++;
                    }
                }
            }


            return InsertCount;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Student getStudentInfoBySid(int bindid) {
        try{
            return studentMapper.selectByPrimaryKey(bindid);
        }catch (Exception E){
            E.printStackTrace();
        }
        return null;
    }


    public static Object formGetCellType(Cell cell){
        Object value=null;
        try{
            if(cell.getCellType()==cell.CELL_TYPE_BLANK){
                value="";
            }else if(cell.getCellType()==cell.CELL_TYPE_BOOLEAN){
                value=cell.getBooleanCellValue();
            }else if(cell.getCellType()==cell.CELL_TYPE_ERROR){
                value="";
            }else if(cell.getCellType()==cell.CELL_TYPE_FORMULA){
                value=cell.getCellFormula();
            }else if(cell.getCellType()==cell.CELL_TYPE_NUMERIC){
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date tempValue = cell.getDateCellValue();
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy/MM/dd");
                    value = simpleFormat.format(tempValue);
                }else {
                    value = String.valueOf(cell.getNumericCellValue());
                }
            }else if(cell.getCellType()==cell.CELL_TYPE_STRING){
                value=cell.getStringCellValue();
            }else{
                value=cell.getDateCellValue();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return value;
    }
}
